<template>
  <div class="shopcart">
    <div class="cart-body">
      <van-checkbox-group @change="groupChange" v-model="result" ref="checkboxGroup">
        <van-swipe-cell :right-width="50" v-for="(item, index) in cartlist" :key="index">
          <div class="good-item">
            <van-checkbox :name="item.cartItemId" />
            <div class="good-img"><img :src="$filters.imgPrefix(item.goodsCoverImg)"></div>
            <div class="good-desc">
              <div class="good-title">
                <span>{{item.goodsName}}</span>
                <span>x{{item.goodsCount}}</span>
              </div>
              <div class="good-btn">
                <div class="price">¥{{item.sellingPrice}}</div>
                <van-stepper
                  integer
                  :min="1"
                  :max="5"
                  :model-value="item.goodsCount"
                  :name="item.cartItemId"
                  async-change
                  @change="modifyCartCount"
                />
              </div>
            </div>
          </div>
          <template #right>
            <van-button
              square
              icon="delete"
              type="danger"
              class="delete-button"
              @click="deleteItem(item.cartItemId)"
            />
          </template>
        </van-swipe-cell>
      </van-checkbox-group>
    </div>
    <van-submit-bar
      v-if="cartlist.length > 0"
      class="submit-all van-hairline--top"
      :price="total * 100"
      button-text="结算"
      @submit="onSubmit"
    >
      <van-checkbox @click="hanleAllCheck" v-model:checked="checkAll">全选</van-checkbox>
    </van-submit-bar>
    <div class="empty" v-if="!cartlist.length">
      <img class="empty-cart" src="https://s.yezgea02.com/1604028375097/empty-car.png" alt="空购物车">
      <div class="title">购物车空空如也</div>
      <van-button 
        round 
        :color="themeStore.primaryColor" 
        type="primary" 
        block 
        @click="$router.push({path: '/home'})"
      >
        前往选购
      </van-button>
    </div>
  </div>
</template>

<script setup>
import {onMounted, computed} from 'vue'
import {useRouter} from 'vue-router'
import useThemeStore from '@/store/theme'
import useShopcart from '@/hooks/useShopcart'

const themeStore = useThemeStore()
const {
  cartlist, result, checked, all, checkAll,
  initShopCart, deleteItem, modifyCartCount, 
  groupChange, hanleAllCheck, onSubmit
} = useShopcart(useRouter())

const total = computed(() => {
  let sum = 0
  let list = cartlist.value.filter(item => result.value.includes(item.cartItemId))
  list.forEach(i => sum += i.goodsCount * i.sellingPrice)
  return sum
})

onMounted(() => initShopCart())
</script>

<style lang="less" scoped>
@import './shopcart.less';
</style>